package com.admin.system.config;

import com.admin.core.dto.DataScope;
import com.admin.oauth.util.DataScopeUtil;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Properties;

/**
 * mybatis 拦截器
 *
 * @author sq-lan
 * @date 2024/07/15
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
})
public class MyBatisExecutorIntercept implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("====intercept======");

        // 不是 select 跳过
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        Object parameter = args[1];
        Map<String, Object> map = (Map) parameter;
        RowBounds rowBounds = (RowBounds) args[2];
        ResultHandler resultHandler = (ResultHandler) args[3];
        Executor executor = (Executor) invocation.getTarget();
        CacheKey cacheKey;
        BoundSql boundSql;
        //由于逻辑关系，只会进入一次
        if (args.length == 4) {
            //4 个参数时
            boundSql = mappedStatement.getBoundSql(parameter);
            cacheKey = executor.createCacheKey(mappedStatement, parameter, rowBounds, boundSql);
        } else {
            //6 个参数时
            cacheKey = (CacheKey) args[4];
            boundSql = (BoundSql) args[5];
        }


        boolean flag = false;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if((entry.getValue() instanceof DataScope)) {
                flag =true;
                break;
            }
        }
        // 没有 DataScope 的子类，跳过添加数据范围
        if(!flag) {
            return executor.query(mappedStatement, parameter, rowBounds, resultHandler, cacheKey, boundSql);
        }

        // id为执行的mapper方法的全路径名，如com.metro.dao.UserMapper.insertUser
        // String id = mappedStatement.getId();
        // 获取到原始sql语句
        String sql = boundSql.getSql();

        // 简单查询 只有一个 select，直接拼接到后面，如果没有 where 要先添加 where 关键字。 如果不是简单查询，将sql 作为子查询。不用管 mysql会自行优化
        // 添加数据范围
        String dataScope = DataScopeUtil.dataScope();
        if(StringUtils.hasText(dataScope)) {
            // 修改后的sql
            sql = "SELECT * FROM (" + sql + ") AS temp where " + dataScope;
        }

        //通过反射修改boundSql对象的sql语句
        Field field = boundSql.getClass().getDeclaredField("sql");
        field.setAccessible(true);
        field.set(boundSql, sql);

        // 执行修改后的sql语句
        return executor.query(mappedStatement, parameter, rowBounds, resultHandler, cacheKey, boundSql);
    }

    @Override
    public Object plugin(Object o) {
        System.out.println("====plugin======");
        if(o instanceof StatementHandler){
            //调用插件
            System.out.println("====StatementHandler======");
        }
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        System.out.println("====setProperties======");
    }
}
